import {reactive, DefineComponent, watch, markRaw} from 'vue';
import {designComponent} from "@/use/designComponent";
import {AppNavigator} from "./app-navigator";

export const AppNavigatorPage = designComponent({
  setup(){
    const navigator = AppNavigator.use.inject(); // 什么时候provide的？ 在app.vue 中 app-navigator挂载时； AppNavigatorPage是AppNavigator的子组件 故能注入

    const state = reactive({
      PageComponent: null as null | DefineComponent
    })

    const utils = {
      reset: async () => {
        const route = navigator.state.route
        if(!route) return;
        let {path} = route;
        if(!path) return;

        if (path.charAt(0) === '/') {
          path = path.slice(1);
        }
        console.log('AppNavigatorPage path:',path);
        const Component = (await import('demo/pages/' + path)).default;
        console.log('AppNavigatorPage PageComponent:',Component);
        state.PageComponent = markRaw(Component)/*Component本身作为一个对象并不需要被代理*/;
      }
    }

    //watch只对响应式数据生效？
    watch(()=>navigator.state.route.path, utils.reset, {immediate: true});

    return {
      render: () => {
        const {PageComponent} = state;
        return !!PageComponent ? <PageComponent/> : null;
      }
    }
  }
})
